package main

import (
	"io"
	"io/ioutil"
	"os"
	"strconv"
	"time"

	"github.com/GoWebDemo/utils"
	"github.com/astaxie/beego/logs"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"github.com/joho/godotenv"
	uuid "github.com/satori/go.uuid"
)

func main() {

	// r := gin.Default()
	// r.GET("/ping", func(c *gin.Context) {
	// 	c.JSON(200, gin.H{
	// 		"message": "pong",
	// 	})
	// })
	// r.Run(":8084") // listen and serve on 0.0.0.0:8080

	// Logging to a file.
	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f)

	logs.SetLogger("console")
	logs.SetLogger(logs.AdapterFile, `{"filename":"project.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10}`)

	// 配置
	err := godotenv.Load()
	if err != nil {
		logs.Error(err)
	}

	// Creates a gin router with default middleware:
	// logger and recovery (crash-free) middleware
	router := gin.Default()

	// This handler will match /user/john but will not match neither /user/ or /user
	// router.GET("/user/:name", func(c *gin.Context) {
	// 	name := c.Param("name")
	// 	c.String(http.StatusOK, "Hello %s", name)
	// })

	router.GET("/redis/get", func(c *gin.Context) {
		key := c.Query("key")
		client := utils.GetClient()
		var code string
		var message string
		val, err := client.Get(key).Result()
		if err == redis.Nil {
			code = "-10000"
			message = "key:" + key + ",value:redis.Nil"
		} else if err != nil {
			//panic(err)
			logs.Error("get exception:", err)
			code = "-10000"
			message = "get exception:" + err.Error()
		} else {
			code = "10000"
			message = "key:" + key + ",value:" + val
		}

		c.JSON(200, gin.H{
			"code":    code,
			"message": message,
		})

		//logs.Warn("json is a type of kv like", map[string]int{"key": 2016})
		//c.String(http.StatusOK, "Hello %s", name)
	})

	router.GET("/redis/set", func(c *gin.Context) {
		key := c.Query("key")
		val := c.Query("value")
		client := utils.GetClient()
		var code string
		var message string
		err := client.Set(key, val, time.Minute).Err()
		if err != nil {
			//panic(err)
			logs.Error("get exception:", err)
			code = "-10000"
			message = "get exception:" + err.Error()
		} else {
			code = "10000"
			message = "key:" + key + ",value:" + val
		}
		c.JSON(200, gin.H{
			"code":    code,
			"message": message,
		})
	})

	router.GET("/redis/del", func(c *gin.Context) {
		key := c.Query("key")
		client := utils.GetClient()
		var code string
		var message string
		err := client.Del(key).Err()
		if err != nil {
			//panic(err)
			logs.Error("get exception:", err)
			code = "-10000"
			message = "get exception:" + err.Error()
		} else {
			code = "10000"
			message = "key:" + key
		}
		c.JSON(200, gin.H{
			"code":    code,
			"message": message,
		})
	})

	router.GET("/home/loadtest", func(c *gin.Context) {
		key := c.Query("timestamp")

		var code string
		var message string

		timestamp := time.Now().Unix()
		timestampStr := strconv.FormatInt(timestamp, 10)

		code = "-10000"
		message = key + "," + timestampStr
		time.Sleep(time.Second * 2)
		c.JSON(200, gin.H{
			"code":    code,
			"message": message,
		})
	})

	router.POST("/redis/defaultdata", func(c *gin.Context) {
		key, _ := uuid.NewV4()
		keyName := key.String()
		val := "<xml><ToUserName><![CDATA[gh_3e600160bbf9]]></ToUserName> <FromUserName><![CDATA[oeB2VjojwenJ_dPeKayzSsVKJong]]></FromUserName> <CreateTime>unixtimestamp</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> <EventKey><![CDATA[qrscene_94705]]></EventKey> <Ticket><![CDATA[gQHw8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyRXZtbTRwVXRhbGUxMDAwME0wM0kAAgSjrXFaAwQAAAAA]]></Ticket> </xml><xml><ToUserName><![CDATA[gh_3e600160bbf9]]></ToUserName> <FromUserName><![CDATA[oeB2VjojwenJ_dPeKayzSsVKJong]]></FromUserName> <CreateTime>unixtimestamp</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> <EventKey><![CDATA[qrscene_94705]]></EventKey> <Ticket><![CDATA[gQHw8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyRXZtbTRwVXRhbGUxMDAwME0wM0kAAgSjrXFaAwQAAAAA]]></Ticket> </xml><xml><ToUserName><![CDATA[gh_3e600160bbf9]]></ToUserName> <FromUserName><![CDATA[oeB2VjojwenJ_dPeKayzSsVKJong]]></FromUserName> <CreateTime>unixtimestamp</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> <EventKey><![CDATA[qrscene_94705]]></EventKey> <Ticket><![CDATA[gQHw8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyRXZtbTRwVXRhbGUxMDAwME0wM0kAAgSjrXFaAwQAAAAA]]></Ticket> </xml>"
		client := utils.GetClient()
		var code string
		var message string

		err := client.Set(keyName, val, time.Hour*100).Err()
		if err != nil {
			//panic(err)
			logs.Error("get exception:", err)
			code = "-10000"
			message = "get exception:" + err.Error()
		} else {
			code = "10000"
			message = "key:" + keyName + ",value:" + val
		}

		c.JSON(200, gin.H{
			"code":    code,
			"message": message,
		})
	})

	router.POST("/wxreceiver/receiver/enter", func(c *gin.Context) {
		params := c.Request.URL.Query()
		var code string
		var message string

		defer c.Request.Body.Close()

		body, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			code = "-10000"
			message = "request erorr:"
			//fmt.Println("request erorr", err)
			logs.Error("request erorr:", err)
		}
		code = "10000"
		message = "ok"
		c.JSON(200, gin.H{
			"code":    code,
			"message": message,
			"params":  params,
			"body":    string(body),
		})
	})

	// By default it serves on :8080 unless a
	// PORT environment variable was defined.
	addr := os.Getenv("ADDR")
	router.Run(":" + addr)
	// router.Run(":3000") for a hard coded port
}
